<?php

namespace App\Http\Controllers\QRTerminal;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Api\Controllers\DevicePay\CanyinController as Canyin;

class IndexController extends BaseController{

    // 终端绑定查询
    function merchBindQuery(Request $request){
        $data = $request->all(); // 获取传值成数组
        if( !isset($data['sn']) || !isset($data['sign']) ){
            return json_encode([
                "code" => 403,
                "message" => "缺少参数",
                'data' => $data
            ]);
        }
        
        $sign_old = $data['sign']; // 先把sign节点的值附值到其它变量
        $sign_verify = $this->sign_verify($data);
        if($sign_verify){
            return $sign_verify; // 签名验证
        }
        
        $sn = DB::table('devices')->where(['device_no' => $data['sn']])->first(); // 查询设备
        if(!$sn){
            return json_encode([
                "code" => 403,
                "message" => "sn不存在",
                'data' => $sn
            ]);
        }
        $pay_amount_e = DB::table('store_pay_ways')->where(['store_id' => $sn->store_id, 'status' => '1', 'ways_source' => 'weixin'])->orderBy('sort', 'asc')->first(); // 交易限额

        $data = [
            'state' => 1,
            "message" => "请求成功",
            'store_name' => $sn->store_name,
            'merch_no' => $sn->store_id,
            'max_limit' => $pay_amount_e?$pay_amount_e->pay_amount_e:50000,
        ];
        
        $sign = $this->get_sign($data);
        $data['sign'] = $sign;
        
        return json_encode([
            "code" => 100,
            "message" => "请求成功",
            'data' => $data,
        ]);
    }
    
    // 二维码扫码支付
    function authcodePay(Request $request){
        $data = $request->all(); // 获取传值成数组
        if( !isset($data['sn']) || !isset($data['sign']) || !isset($data['order_amt']) || !isset($data['order_no']) || !isset($data['auth_no']) ){
            return json_encode([
                "code" => 403,
                "message" => "缺少参数",
                'data' => $data
            ]);
        }
        
        $sign_old = $data['sign']; // 先把sign节点的值附值到其它变量
        $sign_verify = $this->sign_verify($data);
        if($sign_verify){
            return $sign_verify; // 签名验证
        }
        
        $sn = DB::table('devices')->where(['device_no' => $data['sn']])->first(); // 查询设备
        if(!$sn){
            return json_encode([
                "code" => 403,
                "message" => "sn不存在",
                'data' => $sn
            ]);
        }
        $store = DB::table('stores')->where(['store_id' => $sn->store_id])->first();
        if(!$store){
            return json_encode([
                "code" => 403,
                "message" => "设备sn绑定的门店不存在",
                'data' => $store
            ]);
        }
        
        $res = [
            'store_id' => $store->store_id,
            'merchant_id' => $store->merchant_id,
            'code' => $data['auth_no'],
            'total_amount' => $data['order_amt'],
            'device_id' => $sn->device_no,
            'device_type' => $sn->device_type,
            'sign' => '1',
            'other_no' => $data['order_no'],
        ];
        
        
        
        $scan_pay = $this->scan_pay($res);
        
        
        if(isset($scan_pay['result_code'])){
            if($scan_pay['result_code'] == 'SUCCESS'){
                if($scan_pay['ways_source'] == 'alipay'){
                    $pay_state = 1;
                }else if($scan_pay['ways_source'] == 'weixin'){
                    $pay_state = 2;
                }else{
                    $pay_state = 32;
                }
                
                $data = [
                    'state' => 1,
                    'message' => '请求成功',
                    'order_no' => $scan_pay['out_trade_no'],
                    'pay_state' => 1,
                    'pay_type' => $pay_state,
                ];
            }else if($scan_pay['result_code'] == 'USERPAYING'){
                $data = [
                    'state' => 1,
                    'message' => '请求成功',
                    // 'order_no' => $result['out_trade_no'],
                    'pay_state' => 3,
                    // 'pay_type' => $pay_state,
                ];
            }
            
        }else{
            $data = [
                'state' => 1,
                'message' => '请求成功',
                // 'order_no' => $result['out_trade_no'],
                'pay_state' => 2,
                // 'pay_type' => $pay_state,
            ];
        }
        
        $sign = $this->get_sign($data);
        $data['sign'] = $sign;
        
        return json_encode([
            "code" => 100,
            "message" => "请求成功",
            'data' => $data
        ]);
    }
    
    // 二维码扫码支付查询
    function queryPayState(Request $request){
        $data = $request->all(); // 获取传值成数组
        if( !isset($data['sn']) || !isset($data['sign']) || !isset($data['order_no']) ){
            return json_encode([
                "code" => 403,
                "message" => "缺少参数",
                'data' => $data
            ]);
        }
        
        $sign_old = $data['sign']; // 先把sign节点的值附值到其它变量
        $sign_verify = $this->sign_verify($data);
        if($sign_verify){
            return $sign_verify; // 签名验证
        }
        
        $sn = DB::table('devices')->where(['device_no' => $data['sn']])->first(); // 查询设备
        if(!$sn){
            return json_encode([
                "code" => 403,
                "message" => "sn不存在",
                'data' => $sn
            ]);
        }
        $store = DB::table('stores')->where(['store_id' => $sn->store_id])->first();
        if(!$store){
            return json_encode([
                "code" => 403,
                "message" => "设备sn绑定的门店不存在",
                'data' => $store
            ]);
        }
        
        $res = [
            'store_id' => $store->store_id,
            'merchant_id' => $store->merchant_id,
            'out_trade_no' => $data['order_no'],
            'device_id' => $sn->device_no,
            'device_type' => $sn->device_type,
            'sign' => '1',
        ];
        $result = $this->order_query($res);
        
        $data = [];
        if( isset($result['result_code']) ){
            if ($result['result_code'] == 'SUCCESS') {
                if($result['ways_source'] == 'alipay'){
                    $pay_state = 1;
                }else if($result['ways_source'] == 'weixin'){
                    $pay_state = 2;
                }else{
                    $pay_state = 32;
                }
                
                // DB::table('orders')->where([ 'out_trade_no' => $result['out_trade_no'] ])->update([ 'other_no' => $data['order_no'] ]);
                
                $data = [
                    'state' => 1,
                    'message' => $result['return_msg'],
                    'order_no' => $result['out_trade_no'],
                    'pay_state' => 1,
                    'pay_type' => $pay_state,
                ];
            }else if ($result['result_code'] == 'USERPAYING') {
                $data = [
                    'state' => 1,
                    'message' => $result['return_msg'],
                    'order_no' => $result['out_trade_no'],
                    'pay_state' => 3,
                    // 'pay_type' => $pay_state,
                ];
            }else{
                $data = [
                    'state' => 1,
                    'message' => $result['result_msg'],
                    // 'order_no' => $result['out_trade_no'],
                    'pay_state' => 2,
                    // 'pay_type' => $pay_state,
                    // 'sign' => $sign_old,
                ];
        }
        }else{
            $data = [
                'state' => 1,
                'message' => $result['result_msg'],
                // 'order_no' => $result['out_trade_no'],
                'pay_state' => 2,
                // 'pay_type' => $pay_state,
                // 'sign' => $sign_old,
            ];
        }
        
        
        $sign = $this->get_sign($data);
        // file_put_contents('1117.log', var_export($data, true) . "\r\n", FILE_APPEND);
        $data['sign'] = $sign;
        
        return json_encode([
            "code" => 100,
            "message" => "返回成功",
            'data' => $data,
        ]);
    }
    
    // 退款
    function authcodeRefund(Request $request){
        $data = $request->all(); // 获取传值成数组
        if( !isset($data['sn']) || !isset($data['sign']) || !isset($data['out_trade_no']) ){
            return json_encode([
                "code" => 403,
                "message" => "缺少参数",
                'data' => $data
            ]);
        }
        
        $sign_old = $data['sign']; // 先把sign节点的值附值到其它变量
        $sign_verify = $this->sign_verify($data);
        if($sign_verify){
            return $sign_verify; // 签名验证
        }
        
        $sn = DB::table('devices')->where(['device_no' => $data['sn']])->first(); // 查询设备
        if(!$sn){
            return json_encode([
                "code" => 403,
                "message" => "sn不存在",
                'data' => $sn
            ]);
        }
        $store = DB::table('stores')->where(['store_id' => $sn->store_id])->first();
        if(!$store){
            return json_encode([
                "code" => 403,
                "message" => "设备sn绑定的门店不存在",
                'data' => $store
            ]);
        }
        
        $res = [
            'store_id' => $store->store_id,
            'merchant_id' => $store->merchant_id,
            'out_trade_no' => $data['out_trade_no'],
            'device_id' => $sn->device_no,
            'device_type' => $sn->device_type,
            'sign' => '1',
        ];
        $result = $this->refund($res);
        // file_put_contents('1117.log', var_export($data, true) . "\r\n", FILE_APPEND);
        
        $pay_state = '';
        $result['out_trade_no'] = '';
        if($result['return_code']=='FALL'){
            $data = [
                'state' => 1,
                'message' => $result['return_msg'],
                'pay_state' => 2,
            ];
             return json_encode([
                "code" => 100,
                "message" => "返回成功",
                'data' => $data,
            ]);
        }
        
        if ($result['result_code'] == 'FALL') {
            $data = [
                'state' => 1,
                'message' => $result['return_msg'],
                'pay_state' => 2,
                // 'sign' => $sign_old,
            ];
        }else if ($result['result_code'] == 'USERPAYING') {
            $data = [
                'state' => 1,
                'message' => $result['return_msg'],
                // 'order_no' => $result['out_trade_no'],
                'pay_state' => 3,
                // 'pay_type' => $pay_state,
            ];
        }elseif ($result['result_code'] == 'SUCCESS') {
            if($result['ways_source'] == 'alipay'){
                $pay_state = 1;
            }else if($result['ways_source'] == 'weixin'){
                $pay_state = 2;
            }else{
                $pay_state = 32;
            }
            
            $data = [
                'state' => 1,
                'message' => $result['return_msg'],
                // 'order_no' => $result['out_trade_no'],
                'pay_state' => 1,
                'pay_type' => $pay_state,
            ];
        }
        $sign = $this->get_sign($data);
        $data['sign'] = $sign;
        
        return json_encode([
            "code" => 100,
            "message" => "返回成功",
            'data' => $data,
        ]);
    }
    
    // 交易记录查询接口
    function transactionRecord(Request $request){
        $data = $request->all(); // 获取传值成数组
        if( !isset($data['sn']) || !isset($data['query_date']) || !isset($data['query_type']) || !isset($data['page_size']) || !isset($data['page_index']) ){
            return json_encode([
                "code" => 403,
                "message" => "缺少参数",
                'data' => $data
            ]);
        }
        
        // $sign_old = $data['sign']; // 先把sign节点的值附值到其它变量
        // $sign_verify = $this->sign_verify($data);
        // if($sign_verify){
        //     return $sign_verify; // 签名验证
        // }
        
        $sn = DB::table('devices')->where(['device_no' => $data['sn']])->first(); // 查询设备
        if(!$sn){
            return json_encode([
                "code" => 403,
                "message" => "sn不存在",
                'data' => $sn
            ]);
        }
        
        $query_date=$data['query_date'];//日期
        $query_type=$data['query_type'];//0:查询日 1:查询月
        
        if($data['query_type'] == '0'){
            if(date('Y-m-d')==$query_date){
                $where[] = ['created_at', '>=', $query_date.' 00:00:00'];
                $where[] = ['created_at', '<=', $query_date.' 23:59:59'];
                $obj = DB::table('orders');
                $obj->where($where)->where(['store_id' => $sn->store_id])->where(['device_id' => $sn->device_no])->select('out_trade_no', 'created_at', 'total_amount', 'ways_source');
        
                $this->t = $obj->count();
                $data = $this->page($obj)->get()->toArray();
                $this->page_count = ceil($this->t/$this->l);
            }else{
                $where[] = ['created_at', '>=', $query_date.' 00:00:00'];
                $where[] = ['created_at', '<=', $query_date.' 23:59:59'];
                
                $date=date('Ymd',strtotime($query_date));
                $table='orders_'.$date;
                $obj = DB::table($table);
                $obj->where($where)->where(['store_id' => $sn->store_id])->where(['device_id' => $sn->device_no])->select('out_trade_no', 'created_at', 'total_amount', 'ways_source');
        
                $this->t = $obj->count();
                $data = $this->page($obj)->get()->toArray();
                $this->page_count = ceil($this->t/$this->l);
            }
        }else{
            if(date('Y-m')==$query_date){
                $day=date('d');
                $where[] = ['created_at', '>=', $query_date.'-'.'01'.' 00:00:00'];
                $where[] = ['created_at', '<=', $query_date.'-'.$day.' 00:00:00'];
                $obj = DB::table('orders');
                $obj->where($where)->where(['store_id' => $sn->store_id])->where(['device_id' => $sn->device_no])->select('out_trade_no', 'created_at', 'total_amount', 'ways_source');
            
                $this->t = $obj->count();
                $data = $this->page($obj)->get()->toArray();
                $this->page_count = ceil($this->t/$this->l);
            }else{
                $data = [
                    'state' => 1,
                    'message' => '暂不支持往月数据查询',
                ];
            }
        }
        if(!$data){
            $data = [
                'state' => 1,
                'message' => '没有数据',
            ];
            
            return json_encode([
                "code" => 100,
                "message" => "请求成功",
                'data' => $data,
            ]);
        }
        
        foreach($data as $k => $v){
            $datas[$k]['transaction_time'] = $v->created_at;
            $datas[$k]['order_no'] = $v->out_trade_no;
            $datas[$k]['order_amt'] = $v->total_amount;
            $datas[$k]['pay_type'] = $v->ways_source;
        }
        
        
        $data = [
            'state' => 1,
            'datalist_json' => $datas,
            'message' => '请求成功',
            'page_count' => $this->page_count,
            'row_count' => $this->t,
        ];
        
        return json_encode([
            "code" => 100,
            "message" => "返回成功",
            'data' => $data,
        ]);
    }
    
    // 交易汇总查询
    function transactionSummary(Request $request){
        $data = $request->all(); // 获取传值成数组
        file_put_contents('qr68.log',var_export($data,true)."\r\n",FILE_APPEND);
        if( !isset($data['sn']) || !isset($data['query_date']) || !isset($data['query_type']) ){
            return json_encode([
                "code" => 403,
                "message" => "缺少必要参数",
                'data' => $data
            ]);
        }
        
        $sign_old = $data['sign']; // 先把sign节点的值附值到其它变量
        $sign_verify = $this->sign_verify($data);
        if($sign_verify){
            return $sign_verify; // 签名验证
        }
        
        $sn = DB::table('devices')->where(['device_no' => $data['sn']])->first(); // 查询设备
        if(!$sn){
            return json_encode([
                "code" => 403,
                "message" => "sn不存在",
                'data' => $sn
            ]);
        }
        $query_date=$data['query_date'];//日期
        $query_type=$data['query_type'];//0:查询日 1:查询月
        if($query_type == '0'){
            if(date('Y-m-d')==$query_date){
                $where[] = ['created_at', '>=', $query_date.' 00:00:00'];
                $where[] = ['created_at', '<=', $query_date.' 23:59:59'];
                $sum_amount = DB::table('orders')->where(['store_id' => $sn->store_id])->where($where)->whereIn('pay_status', [1])->sum('total_amount');
                $refund_amount = DB::table('orders')->where(['store_id' => $sn->store_id])->where($where)->whereIn('pay_status', [6])->sum('total_amount');
            }else{
                $sum_amount = DB::table('company_day_commission')->where(['store_id' => $sn->store_id])->where(['settling_day'=>$query_date])->sum('total_amount');
                $refund_amount = DB::table('company_day_commission')->where(['store_id' => $sn->store_id])->where(['settling_day'=>$query_date])->sum('refund_amount');
            }
        }else{
            if(date('Y-m')==$query_date){
                $day=date('d');
                $where[] = ['created_at', '>=', $query_date.'-'.$day.' 00:00:00'];
                $where[] = ['created_at', '<=', $query_date.'-'.$day.' 00:00:00'];
                $sum_amount = DB::table('orders')->where(['store_id' => $sn->store_id])->where($where)->whereIn('pay_status', [1])->sum('total_amount');
                $refund_amount = DB::table('orders')->where(['store_id' => $sn->store_id])->where($where)->whereIn('pay_status', [6])->sum('total_amount');
                
                $where1[] = ['settling_day', '>=', $query_date.'-01'];
                $where1[] = ['settling_day', '<=', $query_date.'-'.$day];
                $old_sum_amount=DB::table('company_day_commission')->where(['store_id' => $sn->store_id])->where($where1)->sum('total_amount');
                $old_refund_amount=DB::table('company_day_commission')->where(['store_id' => $sn->store_id])->where($where1)->sum('total_amount');
                $sum_amount=$sum_amount+$old_sum_amount;
                $refund_amount=$refund_amount+$old_refund_amount;
            }else{
                $day=date('d');
                $where1[] = ['settling_day', '>=', $query_date.'-01'];
                $where1[] = ['settling_day', '<=', $query_date.'-'.$day];
                $sum_amount=DB::table('company_day_commission')->where(['store_id' => $sn->store_id])->where($where1)->sum('total_amount');
                $refund_amount=DB::table('company_day_commission')->where(['store_id' => $sn->store_id])->where($where1)->sum('total_amount');
            }
        }
        
        $data = [
            'state' => 1,
            'message' => "返回成功",
            'sum_amount' => $sum_amount,
            'refund_amount' => $refund_amount,
        ];
        
        $sign = $this->get_sign($data);
        $data['sign'] = $sign;
        
        return json_encode([
            "code" => 100,
            "message" => "返回成功",
            'data' => $data,
        ]);
    }
    
    // 商户绑定
    function merchBind(Request $request){
        $data = $request->all(); // 获取传值成数组
        if( !isset($data['sn']) || !isset($data['sign']) || !isset($data['merch_no']) ){
            return json_encode([
                "code" => 403,
                "message" => "缺少参数",
                'data' => $data
            ]);
        }
        
        $sign_old = $data['sign']; // 先把sign节点的值附值到其它变量
        $sign_verify = $this->sign_verify($data);
        if($sign_verify){
            return $sign_verify; // 签名验证
        }
        
        $store = DB::table('stores')->where(['store_id' => $data['merch_no']])->first();
        if(!$store){
            return json_encode([
                "code" => 403,
                "message" => "商户编号不存在",
                'data' => $store
            ]);
        }
        
        $merchant_stores = DB::table('merchant_stores')->where(['store_id' => $data['merch_no']])->first();
        if(!$merchant_stores){
            return json_encode([
                "code" => 403,
                "message" => "该门店未绑定收银员",
                'data' => $store
            ]);
        }
        $merchants = DB::table('merchants')->where([ 'id' => $merchant_stores->merchant_id ])->first();
        
        $deice = DB::table('devices')->insert([ 'type' => 's', 'store_id' => $data['merch_no'], 'store_name' => $store->store_name, 'merchant_id' => $merchants->id, 'merchant_name' => $merchants->name, 'device_no' => $data['sn'], 'device_type' => 'pos_1', 'device_name' => 'qr68(博时结科技)', 'device_key' => $data['sn'], 'status' => 1, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s')]);
        
        if($deice){
            $pay_amount_e = DB::table('store_pay_ways')->where(['store_id' => $data['merch_no'], 'status' => '1', 'ways_source' => 'weixin'])->orderBy('sort', 'asc')->first(); // 交易限额
            
            $data = [
                'state' => 1,
                'message' => "返回成功",
                'store_name' => $store->store_name,
                'max_limit' => $pay_amount_e->pay_amount_e,
                'merch_no' => $data['merch_no'],
            ];
            
            $sign = $this->get_sign($data);
            $data['sign'] = $sign;
            
            return json_encode([
                "code" => 100,
                "message" => "返回成功",
                'data' => $data,
            ]);
        }
    }
}